15. Exercise: Adding the Button

In this exercise, you will add a button to your app the same way we have done in the video.

1. Copy the layout XML code below if you haven’t done so already:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="1" />

</LinearLayout>

2. Add another XML tag for the button:

Make sure you set the text to “Roll” by extracting the string to resources and aligning the button horizontally towards the center of the screen.

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/roll" />

3. Position all views in LinearLayout:

To do so, set the orientation of the LinearLayout to vertical and use layout_gravity to align the elements so they are centered as expected.

android:layout_gravity="center_vertical"
android:orientation="vertical"

If you want to start at this step, you can download this exercise code from: Step.01-Exercise-Adding-the-button.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.01-Solution-Adding-the-button or using this git diff.

Task Description:

Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

Well done!

Solution: Step.01-Solution-Adding-the-button or using this git diff.

Let’s move to the next step.